import React, { useState, useRef } from 'react'
import PageHeader from '../components/PageHeader'
import { wapper } from '../utils/hoc'
import chinaCity from '../utils/chinaCity'
import { doctorUpdate } from '../utils/api'
import { Form, Button, Input, Radio, ImageUploader, CascadePicker, Toast } from 'antd-mobile'
import { FormInstance } from 'antd-mobile/es/components/form'
const baseUrl=import.meta.env.VITE_API_BASE_URL
const Profile: React.FC = () => {
    // 保存图片文件对象
    const [img, setImg] = useState<File>()
    const formRef = useRef<FormInstance>(null)
    // 控制省市区选择器显示状态
    const [visible, setVisible] = useState(false)
    const userInfo = JSON.parse(localStorage.getItem('userLoginInfo') || '{}')
    userInfo.area = `${userInfo.province}-${userInfo.city}-${userInfo.county}`
    // 原始头像地址
    const avatar = userInfo.avatar
    userInfo.avatar = [{ url: `${baseUrl+userInfo.avatar}` }]
    const [initialValues] = useState(userInfo)
    const upload = async (file: File) => {
        // 将图片文件对象保存到img
        setImg(file)
        // 可以在此处完成图片上传过程, 获取一个图片访问地址
        return {
            // 获取图片的临时访问地址
            url: URL.createObjectURL(file),
        }
    }
    const submit = async (values: Partial<DoctorRowType>) => {
        // console.log(values, 'values');
        const payload: any = { id: userInfo.id, ...values }
        if (img) {
            payload.avatar = img
        }
        if (Array.isArray(payload.avatar)) {
            payload.avatar = avatar
        }
        if (values.area) {
            const [province, city, county] = values.area?.split('-')
            payload.province = province
            payload.city = city
            payload.county = county
        }
        delete payload.area
        // {} => FormData
        const fd = new FormData()
        for (let key in payload) {
            fd.append(key, payload[key])
        }
        const { data } = await doctorUpdate(fd)
        if (data.code === 200) {
            Toast.show({
                icon: 'success',
                content: data.msg
            })
            return
        }
        Toast.show({
            icon: 'fail',
            content: data.msg
        })
    }
    return (
        <div>
            <PageHeader><h4>个人信息</h4></PageHeader>
            <CascadePicker
                title='选择地区'
                options={chinaCity}
                visible={visible}
                onClose={() => {
                    setVisible(false)
                }}
                onConfirm={(val, extend) => {
                    console.log('onConfirm', val, extend.items)
                    const area = val.join('-')
                    formRef.current?.setFieldValue('area', area)
                }}
                onSelect={val => {
                    console.log('onSelect', val)
                }}
            />
            <Form onFinish={submit} ref={formRef} initialValues={initialValues} mode="card" layout="horizontal"
                footer={<Button type="submit" shape="rounded" block color="primary">确认提交</Button>}>
                <Form.Item name="avatar" label="头像"
                    rules={[{ required: true, message: "请选择头像" }]}>
                    {/* 
                        value: 默认希望展示的图片数据, 格式必须是数组[{url:'图片地址'}] 
                        upload: 当用户选择了一张图片, 图片对象会自动注入到upload属性对应的方法中, 
                        该方法必须返回一个对象,对象中包含url(图片访问地址), 可以在该方法中完成图片上传
                        maxCount: 设置最多可以上传几张图片
                    */}
                    <ImageUploader
                        maxCount={1}
                        upload={upload}
                    />
                </Form.Item>
                <Form.Item name="name" label="姓名"
                    rules={[{ required: true, message: "请输入姓名" }]}>
                    <Input placeholder='姓名'></Input>
                </Form.Item>
                <Form.Item name="gender" label="性别"
                    rules={[{ required: true, message: "请选择性别" }]}>
                    <Radio.Group>
                        <Radio value={1}>男</Radio>
                        <Radio value={2}>女</Radio>
                    </Radio.Group>
                </Form.Item>
                <Form.Item name="title" label="职称"
                    rules={[{ required: true, message: "请输入职称" }]}>
                    <Input placeholder='职称'></Input>
                </Form.Item>
                <Form.Item name="school" label="毕业院校"
                    rules={[{ required: true, message: "请输入毕业院校" }]}>
                    <Input placeholder="毕业院校"></Input>
                </Form.Item>
                <Form.Item name="area" label="地区"
                    rules={[{ required: true, message: "请选择地区" }]}>
                    {/* 省市区三级联动 */}
                    <Input onClick={() => setVisible(true)} placeholder="地区"></Input>
                </Form.Item>
            </Form>
        </div>
    )
}

export default wapper(Profile, { title: '个人资料', requireLogin: true })